/**************************************************************
  > File Name: sendShmget.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年02月23日 星期三 03时16分19秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <sys/wait.h>

#define PATHNAME "/tmp/out"


int main(int argc, char **argv)
{
	sem_t *semp = NULL;
	key_t key;
	int shmid;
	int proc_id = 1;
	size_t size = 4096;
	int *shmp = NULL;
	pid_t pid;
	int n = 100000LL;

	key = ftok(PATHNAME, proc_id);
	if (key < 0)
	{
		perror("ftok()");
		exit(1);
	}
	
	shmid = shmget(key, size, IPC_CREAT | 0666);
	if (shmid < 0)
	{
		perror("shmget()");
		exit(1);
	}
	
	shmp = shmat(shmid, NULL, 0);
	if (shmp == NULL)
	{
		perror("shmat()");
		exit(1);
	}
	
	*shmp = 0;
	semp = 	(sem_t *)mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	if (semp == NULL)
	{
		perror("mmap()");
		exit(1);
	}

	if (sem_init(semp, 1, 1) < 0)
	{
		perror("sem_init()");
		exit(1);
	}

	pid = fork();
	if (pid < 0)
	{
		perror("fork()");
		exit(1);
	}
	if (pid == 0)
	{
		while (n--)
		{
			sem_wait(semp);
			(*shmp)++;
			sem_post(semp);
		}
		exit(0);
	}

	while (n--)
	{
		sem_wait(semp);
		(*shmp)++;
		sem_post(semp);
	}

	wait(NULL);
	printf("%d\n",*shmp);

	sem_destroy(semp);
	shmdt(shmp);
	munmap(semp, sizeof(sem_t));
    exit(0);
}
